﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MyVideoPlayer.Enums;
using MyVideoPlayer.Models;
using MyVideoPlayer.Services.DI;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using WpfScreenHelper;
using MyVideoPlayer.Views;
using System.Threading.Tasks;
using System.DirectoryServices;

namespace MyVideoPlayer.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject, IDisposable
    {
        [GeneratedRegex(@"[a-zA-Z0-9]+")]
        private static partial Regex DeviceNameRegex();
        #region 自定义字段
        private readonly IOpenFileDialogService? _dialogService;
        private readonly IDispatcherService? _dispatcherService;
        private MainWindowModel _mainWinModel;
        private MediaElement? _media;
        private Task? _mediaTask;// 用于播放任务的取消
        private bool _isDragging = false;// 用于判断是否正在拖动滑块
        private CancellationTokenSource? _playCts;// 用于取消播放任务的令牌源
        private static readonly Random _random = new();
        private string _dataFilePath;
        private static readonly JsonSerializerOptions CachedJsonSerializerOptions = new() { WriteIndented = true };// 缓存的 JSON 序列化选项
        private MultiWinSet? _multiWinSet;
        #endregion
        public string DataFilePath => _dataFilePath;
        private readonly string _screenName;
        #region 命令字段
        public IRelayCommand<bool?> CheckedCommand { get; }
        public IRelayCommand SpeedSetCommand { get; }
        public IRelayCommand ShuffleSetCommand { get; }
        public IRelayCommand RepeatSetCommand { get; }
        public IRelayCommand VolumeSetCommand { get; }
        public IRelayCommand VolumeOffCommand { get; }
        public IRelayCommand MaximizedCommand { get; }
        public IRelayCommand TogglePlayListCommand { get; }
        public IRelayCommand MultiWindowSetCommand { get; }
        public IRelayCommand<object> LoadedCommand { get; }
        public IRelayCommand MediaOpenedCommand { get; }
        public IRelayCommand MediaEndedCommand { get; }
        public IRelayCommand BrowserCommand { get; }
        public IRelayCommand PlayMovieCommand { get; }
        public IRelayCommand RemoveMovieCommand { get; }
        public IRelayCommand AddMovieCommand { get; }
        public IRelayCommand RevmoveAllMoviesCommand { get; }
        public IRelayCommand<object> MouseDoubleClickCommand { get; }
        public IRelayCommand SliderDragStartedCommand { get; }
        public IRelayCommand<object> SliderDragCompletedCommand { get; }
        public IRelayCommand<object> SliderValueChangedCommand { get; }
        public IRelayCommand PlayAndPauseCommand { get; }
        public IRelayCommand<MovieInfo> PlayCommand { get; }
        public IRelayCommand PauseCommand { get; }
        public IRelayCommand StopCommand { get; }
        public IRelayCommand Backward10Command { get; }
        public IRelayCommand Forward10Command { get; }
        public IRelayCommand PreMovieCommand { get; }
        public IRelayCommand NextMovieCommand { get; }
        #endregion

        public MainWindowModel MainWinModel
        {
            get => _mainWinModel;
            set => SetProperty(ref _mainWinModel, value);
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _playCts?.Cancel();
            if (_mediaTask != null && _mediaTask.IsCompleted)
            {
                _mediaTask.Dispose();
            }
            _playCts = null;
            _mediaTask = null;
            _media?.Stop(); // 停止媒体元素
            _media?.Close(); // 关闭媒体元素
            SavePlayListData(); // 保存播放列表数据
            GC.SuppressFinalize(this);// 抑制终结器调用，防止对象被回收时调用终结器
        }
        /// <summary>
        /// 无参构造函数
        /// </summary>
        public MainWindowViewModel() : this(null, null, string.Empty)
        {
            // 设计时用，实际不会用到 _dialogService _dispatcherService
        }

        //~MainWindowViewModel()
        //{
        //    Dispose();
        //}

        /// <summary>
        /// 带参构造函数-服务注入
        /// </summary>
        /// <param name="dialogService"></param>
        /// <param name="dispatcherService"></param>
        public MainWindowViewModel(IOpenFileDialogService? dialogService, IDispatcherService? dispatcherService, string dataFilePath)
        {
            _dialogService = dialogService;
            _dispatcherService = dispatcherService;
            // 初始化媒体窗口模型
            _mainWinModel = CreateDefaultModel();
            _dataFilePath = dataFilePath;
            _screenName = GetPrimarySreenName(); // 获取屏幕信息
            #region 命令初始化
            CheckedCommand = new RelayCommand<bool?>(OnChecked);
            SpeedSetCommand = new RelayCommand(OnSpeedSet);
            ShuffleSetCommand = new RelayCommand(OnShuffleSet);
            RepeatSetCommand = new RelayCommand(OnRepeatSet);
            VolumeSetCommand = new RelayCommand<object>(OnVolumeSet);
            VolumeOffCommand = new RelayCommand(OnVolumeOff);
            MaximizedCommand = new RelayCommand<object>(OnMaximized);
            TogglePlayListCommand = new RelayCommand(OnTogglePlayList);
            MultiWindowSetCommand = new RelayCommand(OnMultiWindowSet);
            LoadedCommand = new RelayCommand<object>(OnLoaded);
            MediaOpenedCommand = new RelayCommand(OnMediaOpened);
            MediaEndedCommand = new RelayCommand(OnMediaEnded);
            BrowserCommand = new RelayCommand(OnBrowser);
            PlayMovieCommand = new RelayCommand<object>(OnPlayMovie);
            AddMovieCommand = new RelayCommand(OnAddMovie);
            RevmoveAllMoviesCommand = new RelayCommand<object>(OnRevmoveAllMovies);
            RemoveMovieCommand = new RelayCommand<object>(OnRemoveMovie);
            MouseDoubleClickCommand = new RelayCommand<object>(OnMouseDoubleClick);
            SliderDragStartedCommand = new RelayCommand(OnSliderDragStarted);
            SliderDragCompletedCommand = new RelayCommand<object>(OnSliderDragCompleted);
            SliderValueChangedCommand = new RelayCommand<object>(OnSliderValueChanged);
            PlayAndPauseCommand = new RelayCommand(OnPlayAndPause);
            PlayCommand = new RelayCommand<MovieInfo>(Play);
            PauseCommand = new RelayCommand(Pause);
            StopCommand = new RelayCommand(Stop);
            Backward10Command = new RelayCommand(OnBackward10);
            Forward10Command = new RelayCommand(OnForward10);
            PreMovieCommand = new RelayCommand(OnPreMovie);
            NextMovieCommand = new RelayCommand(OnNextMovie);
            #endregion
        }
        /// <summary>
        /// 创建默认模型
        /// </summary>
        /// <returns></returns>
        private static MainWindowModel CreateDefaultModel()
        {
            try
            {
                return new MainWindowModel
                {
                    Movies = [],
                    SelectedMovie = null,
                    SelectedMovieUri = null,
                    TotalDuration = 1,
                    CurrentPosition = 0,
                    CurrentDuration = "00:00:00",
                    RemainDuration = "00:00:00",
                    IsPlaying = false,
                    SettingModel = new SettingModel
                    {
                        Volume = 50,
                        Speed = 1,
                        Repeat = RepeatEnum.RepeatOnce,
                        IsShuffle = true,
                        IsAutoPlay = false,
                        IsMaximized = false,
                        IsVisibility = true,
                        IsMultiWindows = false
                    }
                };
            }
            catch
            {
                // 配置异常时使用默认值
                return new MainWindowModel
                {
                    Movies = [],
                    SelectedMovie = null,
                    SelectedMovieUri = null,
                    TotalDuration = 1,
                    CurrentPosition = 0,
                    CurrentDuration = "00:00:00",
                    RemainDuration = "00:00:00",
                    IsPlaying = false,
                    SettingModel = new SettingModel()
                };
            }
        }

        #region 设置
        /// <summary>
        /// 自动播放开关
        /// </summary>
        private void OnChecked(bool? isChecked)
        {
            _mainWinModel.SettingModel.IsAutoPlay = isChecked == true;
        }
        /// <summary>
        /// 倍速设置
        /// </summary>
        private void OnSpeedSet()
        {
            if (_media != null)
            {
                if (_media.SpeedRatio < 2.0)
                {
                    _media.SpeedRatio += 0.5;
                }
                else
                {
                    _media.SpeedRatio = 0.5;
                }
            }
            _mainWinModel.SettingModel.Speed = _media!.SpeedRatio;
        }
        /// <summary>
        /// 随机播放开关
        /// </summary>
        private void OnShuffleSet()
        {
            _mainWinModel.SettingModel.IsShuffle = !_mainWinModel.SettingModel.IsShuffle;
        }
        /// <summary>
        /// 循环播放开关
        /// </summary>
        private void OnRepeatSet()
        {
            _mainWinModel.SettingModel.Repeat = (RepeatEnum)(((int)_mainWinModel.SettingModel.Repeat + 1) % 3);
        }
        /// <summary>
        /// 音量调节开关
        /// </summary>
        private void OnVolumeSet(object? obj)
        {
            if (obj is Popup popup)
            {
                popup.IsOpen = true;
                void handler(object sender, RoutedEventArgs e)
                {
                    popup.IsOpen = false;
                    popup.PreviewLostKeyboardFocus -= handler;
                }
                popup.PreviewLostKeyboardFocus += handler;
            }
        }
        /// <summary>
        /// 设置音量为0（静音）
        /// </summary>
        private void OnVolumeOff()
        {
            if (_media != null)
            {
                _media.Volume = 0;
            }
        }
        /// <summary>
        /// 最大化开关
        /// </summary>
        private void OnMaximized(object? obj)
        {
            _mainWinModel.SettingModel.IsMaximized = !_mainWinModel.SettingModel.IsMaximized;
            if (obj is MainWindow win)
            {
                if (_mainWinModel.SettingModel.IsMaximized)
                {
                    win.WindowStyle = WindowStyle.None;// 无边框窗口样式
                    win.ResizeMode = ResizeMode.NoResize;// 不允许调整大小
                    win.WindowState = WindowState.Maximized;// 最大化窗口
                    win.Topmost = true;
                    _mainWinModel.SettingModel.IsVisibility = false;
                }
                else
                {
                    win.WindowStyle = WindowStyle.SingleBorderWindow;
                    win.ResizeMode = ResizeMode.CanResize;
                    win.WindowState = WindowState.Normal;
                    win.Topmost = false;
                    // 还原时居中
                    CenterWindowOnScreen(win);
                }
            }
        }

        // 新增方法
        private static void CenterWindowOnScreen(MainWindow win)
        {
            // 获取当前屏幕信息（可根据你的ScreenInfo逻辑调整）
            var screen = Screen.FromWindow(win);
            var source = PresentationSource.FromVisual(win);
            var dpiX = source?.CompositionTarget.TransformToDevice.M11 ?? 1.0;
            var dpiY = source?.CompositionTarget.TransformToDevice.M22 ?? 1.0;

            double logicalScreenLeft = screen.WorkingArea.Left / dpiX;
            double logicalScreenTop = screen.WorkingArea.Top / dpiY;
            double logicalScreenWidth = screen.WorkingArea.Width / dpiX;
            double logicalScreenHeight = screen.WorkingArea.Height / dpiY;

            win.Width = 1200;
            win.Height = 800;
            win.Left = logicalScreenLeft + (logicalScreenWidth - win.Width) / 2;
            win.Top = logicalScreenTop + (logicalScreenHeight - win.Height) / 2;
        }
        /// <summary>
        /// 播放列表开关
        /// </summary>
        private void OnTogglePlayList()
        {
            _mainWinModel.SettingModel.IsVisibility = !_mainWinModel.SettingModel.IsVisibility;
        }
        /// <summary>
        /// 多窗口设置
        /// </summary>
        private void OnMultiWindowSet()
        {
            // 检查是否已经存在多窗口设置实例
            if (MultiWinSet.Instance == null)
            {
                var multiWindow = new MultiWinSet(_mainWinModel);
                _mainWinModel.SettingModel.IsMultiWindows = true;
                multiWindow.Show();
            }
            else if (!MultiWinSet.Instance.IsVisible)// 如果实例已存在且被隐藏
            {
                // 显示多窗口设置窗口
                MultiWinSet.Instance.Show();
            }
            else if (MultiWinSet.Instance.IsVisible) // 如果实例已存在且可见
            {
                // 如果已经存在实例，则激活它
                MultiWinSet.Instance.Activate();
            }
        }
        #endregion

        #region 视频元素加载
        /// <summary>
        /// 视频加载
        /// </summary>
        /// <param name="obj"></param>
        private void OnLoaded(object? obj)
        {
            LoadPlayListData();
            if (obj is RoutedEventArgs args)
            {
                var win = args.OriginalSource as MainWindow;
                _media = win!.mediaElement;
                // 窗口最大化得判断添加，其它设置作用在 MediaElement 不需再判断
                if (_mainWinModel.SettingModel.IsMaximized)
                {
                    win.WindowStyle = WindowStyle.None;
                    win.ResizeMode = ResizeMode.NoResize;
                    win.WindowState = WindowState.Maximized;
                    win.Topmost = true;
                    _mainWinModel.SettingModel.IsVisibility = false;
                }
                else
                {
                    win.WindowStyle = WindowStyle.SingleBorderWindow;
                    win.ResizeMode = ResizeMode.CanResize;
                    win.WindowState = WindowState.Normal;
                    win.Topmost = false;
                }
            }
            if (_mainWinModel.SelectedMovieUri != null && _mainWinModel.SettingModel.IsAutoPlay == true)
            {
                var selectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
                this.Play(selectedMovie);
            }

            if (_mainWinModel.SettingModel.IsMultiWindows)
            {
                if (MultiWinSet.Instance == null)
                {
                    _multiWinSet = new MultiWinSet(_mainWinModel);
                    _multiWinSet.Show();
                    _multiWinSet.WindowState = WindowState.Minimized; // 初始状态为最小化
                    _multiWinSet.Closed += (s, e) =>
                    {
                        if (_multiWinSet._multiWinSetViewModel.GetAutoShowedScreenCount() == 0)
                        {
                            _mainWinModel.SettingModel.IsMultiWindows = false; // 关闭时更新设置状态
                        }
                        _multiWinSet = null; // 清理引用
                    };
                }
                else
                {
                    MultiWinSet.Instance.WindowState = WindowState.Minimized; // 如果多窗口设置已存在，则最小化它
                }
            }
        }
        #endregion

        #region 视频组件事件
        /// <summary>
        /// 视频加载，记录视频总时长
        /// </summary>
        private void OnMediaOpened()
        {
            // 记录视频总时长
            _mainWinModel.TotalDuration = _media!.NaturalDuration.TimeSpan.TotalSeconds;
        }
        /// <summary>
        /// 视频到达结尾,将播放状态至为停止状态
        /// </summary>
        private void OnMediaEnded()
        {
            _mainWinModel.IsPlaying = false;
            switch (_mainWinModel.SettingModel.Repeat)
            {
                case RepeatEnum.None:
                    this.Stop();
                    break;
                case RepeatEnum.RepeatOnce:
                    _media!.Position = TimeSpan.FromSeconds(0); // 重置视频播放位置到开头
                    _mainWinModel.Movies.FirstOrDefault(m => m.Id == _mainWinModel.SelectedMovie!.Id)!.CurrentDuration = TimeSpan.Zero; // 更新上一个视频的播放位置
                    this.Play(_mainWinModel.SelectedMovie);
                    break;
                case RepeatEnum.Repeat:
                    if (_mainWinModel.Movies.Count == 0) break;
                    //  随机播放
                    if (_mainWinModel.SettingModel.IsShuffle && _mainWinModel.Movies.Count > 1)
                    {
                        int currentIndex = _mainWinModel.Movies.IndexOf(_mainWinModel.SelectedMovie!);
                        int nextIndex = GetRandomMovieIndex(currentIndex);
                        _mainWinModel.SelectedMovie = _mainWinModel.Movies[nextIndex];
                    }
                    else // 顺序播放
                    {
                        int index = _mainWinModel.Movies.IndexOf(_mainWinModel.SelectedMovie!);
                        index = index + 1 >= _mainWinModel.Movies.Count ? 0 : index + 1;
                        _mainWinModel.SelectedMovie = _mainWinModel.Movies[index];
                    }
                    this.Play(_mainWinModel.SelectedMovie);
                    break;
            }
        }
        /// <summary>
        /// 获取随机播放的下一个视频索引
        /// </summary>
        /// <param name="excludeIndex"></param>
        /// <returns></returns>
        private int GetRandomMovieIndex(int excludeIndex)
        {
            int count = _mainWinModel.Movies.Count;
            int nextIndex;
            do
            {
                nextIndex = _random.Next(count);
            } while (nextIndex == excludeIndex && count > 1);
            return nextIndex;
        }
        #endregion

        #region 浏览视频
        /// <summary>
        /// 添加视频文件
        /// </summary>
        private void OnBrowser()
        {
            var dialog = _dialogService;
            if (dialog!.ShowDialog() == true)
            {
                var files = dialog.FileNames;
                files.ToList().ForEach(file =>
                {
                    var maxid = _mainWinModel.Movies.Count > 0 ? _mainWinModel.Movies.Max(t => t.Id) : 0;
                    if (_mainWinModel.Movies.FirstOrDefault(t => t.URL == file) == null)
                    {
                        _mainWinModel.Movies.Add(new MovieInfo()
                        {
                            Id = maxid + 1,
                            Name = Path.GetFileNameWithoutExtension(file),
                            URL = file
                        });
                    }
                });
            }
        }
        /// <summary>
        /// 播放选中的视频
        /// </summary>
        /// <param name="obj"></param>
        private void OnPlayMovie(object? obj)
        {
            if (obj is MovieInfo movie)
            {
                if (_mainWinModel.SelectedMovieUri == null)
                {
                    this.Play(movie);
                }
                var currentMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri!.LocalPath);
                if (currentMovie!.Id == movie.Id) return;
                UpdateSelectedMovieCurrentDuration();
                this.Play(movie);
            }
        }
        /// <summary>
        /// 移除视频
        /// </summary>
        /// <param name="obj"></param>
        private void OnRemoveMovie(object? obj)
        {
            if (obj is not MovieInfo movie || movie == null || _mainWinModel.Movies.Count == 0)
                return;
            if (_mainWinModel.SelectedMovieUri == null)
            {
                _mainWinModel.Movies.Remove(movie);
                return;
            }

            // 如果移除的是当前播放的视频
            if (_mainWinModel.SelectedMovieUri.LocalPath == movie.URL)
            {
                _media!.Pause();//此处不用this.Pause()，因为可能会在播放列表中点击暂停按钮
                _mainWinModel.Movies.Remove(movie);
                var count = _mainWinModel.Movies.Count;// 获取剩余视频数量
                if (count == 0)
                {
                    RestManiWindowModel();
                    return;
                }
                // 选中下一个视频（优先后一个，否则第一个） 
                var nextMovie = _mainWinModel.Movies.FirstOrDefault(m => m.Id > movie.Id) ?? _mainWinModel.Movies.FirstOrDefault();
                this.Play(nextMovie);
                // 当前播放的视频显示为选中状态
                _mainWinModel.SelectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri!.LocalPath);
            }
            else
            {
                // 先移除
                _mainWinModel.Movies.Remove(movie);
            }
            // 当前播放的视频显示为选中状态
            _mainWinModel.SelectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri!.LocalPath);
        }
        /// <summary>
        /// 添加视频命令
        /// </summary>
        private void OnAddMovie()
        {
            OnBrowser();
        }
        /// <summary>
        /// 移除所有视频
        /// </summary>
        /// <param name="obj"></param>
        private void OnRevmoveAllMovies(object? obj)
        {
            if (_mainWinModel.Movies.Count > 0)
            {
                if (_mainWinModel.IsPlaying)
                {
                    this.Stop();
                }
                _mainWinModel.Movies.Clear();
                RestManiWindowModel();
            }
        }
        /// <summary>
        /// 重置当前媒体的状态信息
        /// </summary>
        private void RestManiWindowModel()
        {
            _mainWinModel.SelectedMovie = null;
            _mainWinModel.SelectedMovieUri = null;
            _mainWinModel.TotalDuration = 1;
            _mainWinModel.CurrentPosition = 0;
            _mainWinModel.CurrentDuration = "00:00:00";
            _mainWinModel.RemainDuration = "00:00:00";
            _mainWinModel.IsPlaying = false;
        }
        #endregion

        #region 双击列表打开视频
        private void OnMouseDoubleClick(object? obj)
        {
            if (obj is MovieInfo movie)
            {
                if (_mainWinModel.SelectedMovieUri == null)
                {
                    this.Play(movie);
                }
                var currentMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri!.LocalPath);
                if (currentMovie!.Id == movie.Id) return;
                UpdateSelectedMovieCurrentDuration();
                this.Play(movie);
            }
        }
        #endregion

        #region 进度条操作
        /// <summary>
        /// 拖动开始
        /// </summary>
        private void OnSliderDragStarted()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            _isDragging = true;
            _mainWinModel.IsPlaying = false;
            _media!.Pause();
        }
        /// <summary>
        /// 拖动完成
        /// </summary>
        private void OnSliderDragCompleted(object? obj)
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            _isDragging = false;
            if (obj is double value && _media != null && _media.NaturalDuration.HasTimeSpan)
            {
                _media.Position = TimeSpan.FromSeconds(value);
            }
            _mainWinModel.IsPlaying = true;
            _media?.Play();
            StartProgressSyncTask();
        }

        /// <summary>
        /// 拖动值变动
        /// </summary>
        private void OnSliderValueChanged(object? obj)
        {
            if (_isDragging && obj is double value && _media != null && _media.NaturalDuration.HasTimeSpan)
            {
                _media.Position = TimeSpan.FromSeconds(value);
                _mainWinModel.CurrentDuration = _media.Position.ToString(@"hh\:mm\:ss");
                _mainWinModel.RemainDuration = TimeSpan.FromSeconds(_mainWinModel.TotalDuration - value).ToString(@"hh\:mm\:ss");
            }
        }
        #endregion

        #region 播放控制命令
        /// <summary>
        /// 进度度同步任务
        /// </summary>
        private void StartProgressSyncTask()
        {
            _playCts?.Cancel();
            _playCts = new CancellationTokenSource();
            var token = _playCts.Token;
            _mediaTask = Task.Run(async () =>
            {
                while (_mainWinModel.IsPlaying && !token.IsCancellationRequested)
                {
                    _dispatcherService!.Invoke(() =>
                    {
                        if (!_isDragging)
                        {
                            _mainWinModel.CurrentPosition = _media!.Position.TotalSeconds;
                            _mainWinModel.CurrentDuration = _media.Position.ToString(@"hh\:mm\:ss");
                            _mainWinModel.RemainDuration = TimeSpan.FromSeconds(_mainWinModel.TotalDuration - _media.Position.TotalSeconds).ToString(@"hh\:mm\:ss");
                        }
                    });
                    await Task.Delay(200, token);
                }
            }, token);
        }
        /// <summary>
        /// 播放视频命令
        /// </summary>
        /// <param name="selectedMovie"></param>
        private void Play(MovieInfo? selectedMovie)
        {
            if (selectedMovie == null || _media == null) return;
            _mainWinModel.SelectedMovie = selectedMovie;
            _mainWinModel.SelectedMovieUri = new Uri(selectedMovie.URL!, UriKind.RelativeOrAbsolute);
            _media.Position = _mainWinModel.Movies.FirstOrDefault(m => m.Id == selectedMovie.Id)!.CurrentDuration;
            _mainWinModel.IsPlaying = true;
            _media.Play();
            //Debug.Assert(this._isDragging);
            // 启动一个任务来更新界面的视频播放进度数据
            StartProgressSyncTask();
        }
        /// <summary>
        /// 暂停控制命令
        /// </summary>
        private void Pause()
        {
            _media!.Pause();
            _mainWinModel.IsPlaying = false;
            UpdateSelectedMovieCurrentDuration();
        }
        /// <summary>
        /// 停止控制命令
        /// </summary>
        private void Stop()
        {
            _media!.Stop();
            _mainWinModel.IsPlaying = false;
            UpdateSelectedMovieCurrentDuration();
        }
        /// <summary>
        /// 播放暂停控制命令
        /// </summary>
        private void OnPlayAndPause()
        {
            while (_mainWinModel.Movies.Count < 1)
            {
                OnBrowser();
            }
            _mainWinModel.SelectedMovie ??= _mainWinModel.Movies[0]; ;
            if (!_mainWinModel.IsPlaying)
            {
                Play(_mainWinModel.SelectedMovie);
            }
            else
            {
                Pause();
            }
        }
        /// <summary>
        /// 视频后退10秒
        /// </summary>
        private void OnBackward10()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            this.Pause();
            var newPosition = _media!.Position - TimeSpan.FromSeconds(10);
            _media.Position = newPosition > TimeSpan.Zero ? newPosition : TimeSpan.FromSeconds(0);
            UpdateSelectedMovieCurrentDuration();
            var selectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
            this.Play(selectedMovie!);
        }
        /// <summary>
        /// 视频前进10秒
        /// </summary>
        private void OnForward10()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            this.Pause();
            var newPosition = _media!.Position + TimeSpan.FromSeconds(10);
            _media.Position = newPosition < _media.NaturalDuration.TimeSpan ? newPosition : _media.NaturalDuration.TimeSpan;
            UpdateSelectedMovieCurrentDuration();
            var selectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
            this.Play(selectedMovie!);
        }
        /// <summary>
        /// 播放上一个视频
        /// </summary>
        private void OnPreMovie()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            var currentMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
            var currentIndex = _mainWinModel.Movies.IndexOf(currentMovie!);
            if (currentIndex > 0)
            {
                var preMovie = _mainWinModel.Movies[currentIndex - 1];
                UpdateSelectedMovieCurrentDuration();
                this.Play(preMovie);
            }
        }
        /// <summary>
        /// 播放下一个视频
        /// </summary>
        private void OnNextMovie()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            var currentMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
            var currentIndex = _mainWinModel.Movies.IndexOf(currentMovie!);
            if (currentIndex < _mainWinModel.Movies.Count - 1)
            {
                var nextMovie = _mainWinModel.Movies[currentIndex + 1];
                UpdateSelectedMovieCurrentDuration();
                this.Play(nextMovie);
            }
        }
        #endregion

        #region 加载视频播放列表
        /// <summary>
        /// 更新当前选中视频的播放位置
        /// </summary>
        private void UpdateSelectedMovieCurrentDuration()
        {
            if (_mainWinModel.SelectedMovieUri == null) return;
            var selectedMovie = _mainWinModel.Movies.FirstOrDefault(m => m.URL == _mainWinModel.SelectedMovieUri.LocalPath);
            _mainWinModel.Movies.FirstOrDefault(m => m.Id == selectedMovie!.Id)!.CurrentDuration = _media!.Position;
        }
        /// <summary>
        /// 异步保存播放列表数据
        /// </summary>
        public void SavePlayListData()
        {
            try
            {
                MainWinModel.IsPlaying = false;
                Directory.CreateDirectory(Path.GetDirectoryName(_dataFilePath)!);
                var json = JsonSerializer.Serialize(MainWinModel, CachedJsonSerializerOptions);
                File.WriteAllText(_dataFilePath, json);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("保存播放数据失败: " + ex.Message);
            }
        }
        /// <summary>
        /// 异步加载播放列表数据
        /// </summary>
        public void LoadPlayListData()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_dataFilePath))
                {
                    _dataFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyVideoPlayer", $"PlayList_{_screenName}.json");
                }
                if (!File.Exists(_dataFilePath))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(_dataFilePath)!);
                    var json = JsonSerializer.Serialize(_mainWinModel, CachedJsonSerializerOptions);
                    File.WriteAllText(_dataFilePath, json);
                    return;
                }
                var jsonData = File.ReadAllText(_dataFilePath);

                var model = JsonSerializer.Deserialize<MainWindowModel>(jsonData, CachedJsonSerializerOptions);
                // 此处需使用MainWindowModel，不可赋值给_mainWindowModel，因为它是一个ObservableObject，直接赋值会导致UI无法更新
                MainWinModel = model ?? CreateDefaultModel();
                // 重定向 SelectedMovie 到 Movies 集合中的对象
                if (_mainWinModel.SelectedMovie != null && _mainWinModel.Movies != null)
                {
                    var selectecMovie = _mainWinModel.Movies.FirstOrDefault(m => m.Id == _mainWinModel.SelectedMovie.Id);
                    _mainWinModel.SelectedMovie = selectecMovie;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("加载播放数据失败: " + ex.Message);
                MainWinModel = CreateDefaultModel();
            }
        }
        /// <summary>
        /// 获取屏幕信息
        /// </summary>
        private static string GetPrimarySreenName()
        {
            var screens = Screen.AllScreens;
            return DeviceNameRegex().Match(screens.ToList().FirstOrDefault(s => s.Primary)?.DeviceName!).Value ?? "PrimaryScreen";
        }
        #endregion
    }
}